package pers.bc.utils.net;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import pers.bc.utils.cons.PubConsUtilbc;
import pers.bc.utils.constant.IPubCons;
import pers.bc.utils.encrypt.Base64;
import pers.bc.utils.file.FileUtilbc;
import pers.bc.utils.file.StreamUtil;
import pers.bc.utils.pub.JudgeAssertUtil;
import pers.bc.utils.pub.LoggerUtil;
import pers.bc.utils.pub.PubEnvUtil;
import pers.bc.utils.pub.RandomUtil;
import pers.bc.utils.pub.StringUtil;

/**
 * 网络文件处理工具类
 **
 * @qualiFild pers.bc.utils.net.HttpFileUtil.java<br>
 * @author：LiBencheng<br>
 * @date Created on 2024-10-29<br>
 * @version 1.0<br>
 */
public class HttpFileUtil
{
    
    static String folder = "HttpFileLogs";
    static LoggerUtil logger = LoggerUtil.getInstance(folder);
    
    /**
     * *********************************************************** <br>
     * *说明：以流的方式下载 <br>
     * @see <br>
     * @param path
     * @param response
     * @return <br>
     * @HttpServletResponse <br>
     * @methods pers.bc.utils.net.HttpFileUtil#download <br>
     * @author LiBencheng <br>
     * @date Created on 2024-10-29 <br>
     * @time 下午10:10:40 <br>
     * @version 1.0 <br>
     *************************************************************          <br>
     */
    public static HttpServletResponse download(String path, HttpServletResponse response)
    {
        OutputStream toClient = null;
        try
        {
            // path是指欲下载的文件的路径。
            File file = new File(path);
            // 取得文件名。
            String filename = file.getName();
            // 取得文件的后缀名。
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
        }
        catch (IOException th)
        {
            JudgeAssertUtil.throwExceptionDir(th, folder);
        }
        finally
        {
            FileUtilbc.flush(toClient);
            FileUtilbc.close(toClient);
        }
        return response;
    }
    
    /**
     * *********************************************************** <br>
     * *说明：下载本地文件 <br>
     * @see <br>
     * @param response
     * @param name 文件的存放路径
     * @throws FileNotFoundException <br>
     * @void <br>
     * @methods pers.bc.utils.net.HttpFileUtil#downloadLocal <br>
     * @author LiBencheng <br>
     * @date Created on 2024-10-29 <br>
     * @time 下午10:20:40 <br>
     * @version 1.0 <br>
     *************************************************************          <br>
     */
    public static void downloadLocal(HttpServletResponse response, String name) throws FileNotFoundException
    {
        // 下载本地文件
        String fileName = "Operator.doc".toString(); // 文件的默认保存名
        // 读到流中
        InputStream inStream = new FileInputStream(name);// 文件的存放路径
        // 设置输出的格式
        response.reset();
        response.setContentType("bin");
        response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        // 循环取出流中的数据
        byte[] b = new byte[100];
        int len = 0;
        try
        {
            while ((len = inStream.read(b)) > 0)
                response.getOutputStream().write(b, 0, len);
        }
        catch (IOException th)
        {
            JudgeAssertUtil.throwExceptionDir(th, folder);
        }
        finally
        {
            FileUtilbc.close(inStream);
        }
    }
    
    /**
     * *********************************************************** <br>
     * *说明： 下载网络文件 <br>
     * @see <br>
     * @param response
     * @param httpUrl <br>
     * @void <br>
     * @methods pers.bc.utils.net.HttpFileUtil#downLoadFile <br>
     * @author LiBencheng <br>
     * @date Created on 2024-10-29 <br>
     * @time 下午10:24:51 <br>
     * @version 1.0 <br>
     *************************************************************          <br>
     */
    public static void downLoadFile(HttpServletResponse response, String httpUrl)
    {
        ServletOutputStream out = null;
        InputStream inputStream = null;
        BufferedReader in = null;// 读取响应输入流
        HttpURLConnection httpConn = null;
        try
        {
            httpConn = getHttpConnection(httpUrl);
            InputStream inStream = httpConn.getInputStream();
            
            // 1.设置文件ContentType类型，这样设置，会自动判断下载文件类型
            response.setContentType("multipart/form-data");
            out = response.getOutputStream();
            // 读取文件流
            int len = 0;
            byte[] buffer = new byte[1024 * 10];
            while ((len = inputStream.read(buffer)) != -1)
                out.write(buffer, 0, len);
            
        }
        catch (Throwable th)
        {
            JudgeAssertUtil.throwExceptionDir(th, folder);
        }
        finally
        {
            FileUtilbc.flush(out);
            FileUtilbc.close(out, in, inputStream);
        }
    }
    
    /**
     * *********************************************************** <br>
     * *说明： 三、 下载网络文件，使用NIO下载文件<br>
     * @see <br>
     * @param httpUrl 网络地址URL <br>
     * @param name 文件绝对地址(文件的存放路径) <br>
     * @throws MalformedURLException <br>
     * @void <br>
     * @methods pers.bc.utils.net.HttpFileUtil#downloadNet <br>
     * @author LiBencheng <br>
     * @date Created on 2024-10-29 <br>
     * @time 下午10:19:13 <br>
     * @version 1.0 <br>
     *************************************************************          <br>
     */
    public static void downloadNet(String httpUrl, String name) throws MalformedURLException
    {
        // 下载网络文件
        int bytesum = 0;
        int byteread = 0;
        // URL url = new URL("windine.blogdriver.com/logo.gif");
        FileOutputStream fos = null;
        PrintWriter out = null;
        BufferedReader in = null;// 读取响应输入流
        HttpURLConnection httpConn = null;
        try
        {
            httpConn = getHttpConnection(httpUrl);
            InputStream inStream = httpConn.getInputStream();
            // 获取HttpURLConnection对象对应的输出流
            out = new PrintWriter(httpConn.getOutputStream());
            // // 发送请求参数
            // out.write(params);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应，设置编码方式
            in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
            
            fos = new FileOutputStream(name);
            byte[] buffer = new byte[1204];
            int length = 0;
            while ((byteread = inStream.read(buffer)) != -1)
            {
                bytesum += byteread;
                System.out.println(bytesum);
                fos.write(buffer, 0, byteread);
            }
        }
        catch (Throwable th)
        {
            JudgeAssertUtil.throwExceptionDir(th, folder);
        }
        finally
        {
            FileUtilbc.close(fos, out, in);
            httpConn.disconnect();
        }
    }
    
    /**
     * *********************************************************** <br>
     * *说明：在线打开的方式 <br>
     * @see <br>
     * @param filePath
     * @param response
     * @param isOnLine
     * @throws Exception <br>
     * @void <br>
     * @methods pers.bc.utils.net.HttpFileUtil#downLoad <br>
     * @author LiBencheng <br>
     * @date Created on 2024-10-29 <br>
     * @time 下午10:25:56 <br>
     * @version 1.0 <br>
     *************************************************************          <br>
     */
    public static void downLoad(String filePath, HttpServletResponse response, boolean isOnLine) throws Exception
    {
        BufferedInputStream br = null;
        OutputStream out = null;
        try
        {
            File f = new File(filePath);
            if (!f.exists())
            {
                response.sendError(404, "File not found!");
                return;
            }
            br = new BufferedInputStream(new FileInputStream(f));
            byte[] buf = new byte[1024];
            int len = 0;
            response.reset(); // 非常重要
            if (isOnLine)
            { // 在线打开方式
                URL u = new URL("file:///" + filePath);
                response.setContentType(u.openConnection().getContentType());
                response.setHeader("Content-Disposition", "inline; filename=" + f.getName());
                // 文件名应该编码成UTF-8
            }
            else
            { // 纯下载方式
                response.setContentType("application/x-msdownload");
                response.setHeader("Content-Disposition", "attachment; filename=" + f.getName());
            }
            out = response.getOutputStream();
            while ((len = br.read(buf)) > 0)
                out.write(buf, 0, len);
            
        }
        catch (Throwable th)
        {
            JudgeAssertUtil.throwExceptionDir(th, folder);
        }
        finally
        {
            FileUtilbc.close(br, out);
        }
    }
    
    /**
     * *********************************************************** <br>
     * *说明： 使用传统io stream下载文件<br>
     * @see <br>
     * @param httpUrl
     * @param saveDir
     * @param fileName <br>
     * @void <br>
     * @methods pers.bc.utils.net.HttpFileUtil#downloadByIO <br>
     * @author LiBencheng <br>
     * @date Created on 2024-10-29 <br>
     * @time 下午11:11:39 <br>
     * @version 1.0 <br>
     *************************************************************          <br>
     */
    public static void downloadByIO(String httpUrl, String saveDir, String fileName)
    {
        BufferedOutputStream bos = null;
        InputStream inStream = null;
        try
        {
            byte[] buff = new byte[8192];
            inStream = getHttpConnection(httpUrl).getInputStream();
            File file = new File(saveDir, fileName);
            file.getParentFile().mkdirs();
            bos = new BufferedOutputStream(new FileOutputStream(file));
            int count = 0;
            while ((count = inStream.read(buff)) != -1)
                bos.write(buff, 0, count);
            
        }
        catch (Throwable th)
        {
            JudgeAssertUtil.throwExceptionDir(th, folder);
        }
        finally
        {
            FileUtilbc.close(bos, inStream);
        }
    }
    
    /**
     * *********************************************************** <br>
     * *说明： 使用Byte Array获得stream下载文件<br>
     * @see <br>
     * @param httpUrl
     * @param fileName
     * @param savePath @ * <br>
     * @void <br>
     * @methods pers.bc.utils.net.HttpFileUtil#downLoadFromUrl <br>
     * @author LiBencheng <br>
     * @date Created on 2024-10-29 <br>
     * @time 下午11:17:48 <br>
     * @version 1.0 <br>
     *************************************************************          <br>
     */
    public static void downLoadFromUrl(String httpUrl, String fileName, String savePath)
    {
        FileOutputStream output = null;
        ByteArrayOutputStream bos = null;
        try
        {
            HttpURLConnection conn = getHttpConnection(httpUrl);
            // 得到输入流
            InputStream input = conn.getInputStream();
            // 获取自己数组
            byte[] getData = new byte[10240];
            int len = 0;
            bos = new ByteArrayOutputStream();
            while ((len = input.read(getData)) != -1)
                bos.write(getData, 0, len);
            
            // 文件保存位置
            File saveDir = new File(savePath);
            if (!saveDir.exists()) saveDir.mkdir();
            File file = new File(saveDir + File.separator + fileName);
            output = new FileOutputStream(file);
            output.write(getData);
        }
        catch (Throwable th)
        {
            JudgeAssertUtil.throwExceptionDir(th, folder);
        }
        finally
        {
            FileUtilbc.flush(bos, bos, output);
            FileUtilbc.close(bos, bos, output);
        }
        System.out.println("download success!!");
    }
    
    /**
     * *********************************************************** <br>
     * *说明：使用NIO下载文件 <br>
     * @see <br>
     * @param url
     * @param saveDir
     * @param fileName <br>
     * @void <br>
     * @methods pers.bc.utils.net.HttpFileUtil#downloadByNIO <br>
     * @author LiBencheng <br>
     * @date Created on 2024-10-29 <br>
     * @time 下午11:20:41 <br>
     * @version 1.0 <br>
     *************************************************************          <br>
     */
    public static void downloadByNIO(String url, String saveDir, String fileName)
    {
        ReadableByteChannel rbc = null;
        FileOutputStream fos = null;
        FileChannel foutc = null;
        
        try
        {
            rbc = Channels.newChannel(new URL(url).openStream());
            fileName = PubEnvUtil.isEmpty(fileName) ? RandomUtil.number(20) : fileName;
            File file = new File(saveDir, fileName);
            file.getParentFile().mkdirs();
            fos = new FileOutputStream(file);
            foutc = fos.getChannel();
            foutc.transferFrom(rbc, 0, Long.MAX_VALUE);
            
        }
        catch (Throwable th)
        {
            JudgeAssertUtil.throwExceptionDir(th, folder);
        }
        finally
        {
            FileUtilbc.close(rbc, fos, foutc);
        }
        
    }
    
    /**
     * *********************************************************** <br>
     * *说明： 使用NIO下载文件<br>
     * @see <br>
     * @param httpUrl
     * @param saveDir
     * @param fileName <br>
     * @void <br>
     * @methods pers.bc.utils.net.HttpFileUtil#downloadByNIO2 <br>
     * @author LiBencheng <br>
     * @date Created on 2024-10-29 <br>
     * @time 下午11:22:56 <br>
     * @version 1.0 <br>
     *************************************************************          <br>
     */
    public static void downloadByNIO2(String httpUrl, String saveDir, String fileName)
    {
        InputStream inStream = null;
        HttpURLConnection httpConn = null;
        try
        {
            httpConn = getHttpConnection(httpUrl);
            inStream = httpConn.getInputStream();
            fileName = PubEnvUtil.isEmpty(fileName) ? RandomUtil.number(20) : fileName;
            Path target = Paths.get(saveDir, fileName);
            Files.createDirectories(target.getParent());
            Files.copy(inStream, target, StandardCopyOption.REPLACE_EXISTING);
            
        }
        catch (Throwable th)
        {
            JudgeAssertUtil.throwExceptionDir(th, folder);
        }
        finally
        {
            FileUtilbc.close(inStream);
        }
        
    }
    
    /**
     * *********************************************************** <br>
     * *说明： 下载的文件直接上传到指定的地方, 不需要下载到临时文件夹 <br>
     * @see <br>
     * @param downUrl 下载文件url
     * @param uploadUrl 上传文件url @ * <br>
     * @void <br>
     * @methods pers.bc.utils.net.HttpFileUtil#uploadFileNet <br>
     * @author LiBencheng <br>
     * @date Created on 2024-10-29 <br>
     * @time 下午11:26:12 <br>
     * @version 1.0 <br>
     *************************************************************          <br>
     */
    public static String uploadFileNet(String downUrl, String fileName, String uploadUrl, String cookie)
    {
        InputStream downInStream = null;
        OutputStream uploadOutput = null;
        HttpURLConnection downConn = null;
        HttpURLConnection uploadConn = null;
        PrintWriter writer = null;
        String str = "";
        try
        {
            String boundary = Long.toHexString(System.currentTimeMillis()); // 随机边界
            downConn = getHttpConnection(downUrl);
            // 从连接的输入流中取得回执信息
            downInStream = downConn.getInputStream();
            // Path target = Paths.get(saveDir, fileName);
            // Files.createDirectories(target.getParent());
            // Files.copy(downInStream, target, StandardCopyOption.REPLACE_EXISTING);
            // File file = target.toFile();
            
            // 根据员工ID获取cookie，用于身份验证。Opan yht_access_token
            // put("businessType", "znbzbx_tallydata");// 应用code或业务code，即邮件申请的code 示例：test
            // put("businessId", uuid);// 单据id，和应用code一起唯一识别查询单据文件信息 示例：123
            // 如果cookie有效，则上传合同文件并更新合同的电子签名状态。
            if (PubEnvUtil.isNotEmptyObj(cookie))
            {
                String yht_access_token = StringUtil.valueOfEmpty(cookie);
                OkHttpClient client = new OkHttpClient();
                RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                    .addFormDataPart("files", fileName,
                        RequestBody.create(MediaType.parse("application/octet-stream"), StreamUtil.InputStreamTOByte(downInStream)))
                    .build();
                Request request =
                    new Request.Builder().url(uploadUrl).addHeader("yht_access_token", yht_access_token).post(requestBody).build();
                Response response = client.newCall(request).execute();
                
                if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
                // 删除临时文件。
                // Files.deleteIfExists(Paths.get(file.getPath()));
                ResponseBody body1 = (ResponseBody) response.body();
                str = StreamUtil.InputStreamTOString(((okhttp3.ResponseBody) body1).byteStream(), "utf-8");
            }
        }
        catch (Throwable th)
        {
            JudgeAssertUtil.throwExceptionDir(th, folder);
        }
        finally
        {
            FileUtilbc.close(downInStream, uploadOutput, writer);
            // assert downConn != null;
            // downConn.disconnect();
            // assert uploadConn != null;
            // uploadConn.disconnect();
        }
        
        return str;
    }
    
    /**
     * *********************************************************** <br>
     * *说明：下载的文件直接上传到指定的地方, 需要下载到临时文件夹 <br>
     * @see <br>
     * @param downUrl 下载文件url
     * @param uploadUrl 上传文件url @ * <br>
     * @void <br>
     * @methods pers.bc.utils.net.HttpFileUtil#uploadFileNet <br>
     * @author LiBencheng <br>
     * @date Created on 2024-10-29 <br>
     * @time 下午11:26:12 <br>
     * @version 1.0 <br>
     *************************************************************          <br>
     */
    public static String uploadFileByTemp(String downUrl, String fileName, String uploadUrl, String cookie)
    {
        InputStream downInStream = null;
        OutputStream uploadOutput = null;
        HttpURLConnection downConn = null;
        HttpURLConnection uploadConn = null;
        PrintWriter writer = null;
        String str = "";
        File file = null;
        FileOutputStream fileOutputStream = null;
        BufferedInputStream inStream = null;
        try
        {
            String boundary = Long.toHexString(System.currentTimeMillis()); // 随机边界
            // downConn = getHttpConnection(downUrl);
            // 从连接的输入流中取得回执信息
            // downInStream = downConn.getInputStream();
            Path target = Paths.get(FileUtilbc.getWorkServerPath() + File.separator + "fileTemp", fileName);
            Files.createDirectories(target.getParent());
            // Files.copy(downInStream, target, StandardCopyOption.REPLACE_EXISTING);
            
            URL url = new URL(downUrl);
            inStream = new BufferedInputStream(url.openStream());
            fileOutputStream =
                new FileOutputStream(FileUtilbc.getWorkServerPath() + File.separator + "fileTemp" + File.separator + fileName);
            byte dataBuffer[] = new byte[4096];
            int bytesRead;
            while ((bytesRead = inStream.read(dataBuffer, 0, 4096)) != -1)
            {
                fileOutputStream.write(dataBuffer, 0, bytesRead);
            }
            file = target.toFile();
            final byte[] bytes = StreamUtil.readFileToByteArray(file);
            // final byte[] bytes = StreamUtil.InputStreamTOByte(downInStream);
            // 根据员工ID获取cookie，用于身份验证。Opan yht_access_token
            // put("businessType", "znbzbx_tallydata");// 应用code或业务code，即邮件申请的code 示例：test
            // put("businessId", uuid);// 单据id，和应用code一起唯一识别查询单据文件信息 示例：123
            // 如果cookie有效，则上传合同文件并更新合同的电子签名状态。
            if (PubEnvUtil.isNotEmptyObj(cookie))
            {
                String yht_access_token = StringUtil.valueOfEmpty(cookie);
                OkHttpClient client = new OkHttpClient();
                RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                    .addFormDataPart("files", fileName, RequestBody.create(MediaType.parse("application/octet-stream"), bytes)).build();
                Request request =
                    new Request.Builder().url(uploadUrl).addHeader("yht_access_token", yht_access_token).post(requestBody).build();
                Response response = client.newCall(request).execute();
                
                if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
                // 删除临时文件。
                // Files.deleteIfExists(Paths.get(file.getPath()));
                FileUtilbc.deleteFile(file);
                ResponseBody body1 = (ResponseBody) response.body();
                str = StreamUtil.InputStreamTOString(((okhttp3.ResponseBody) body1).byteStream(), "utf-8");
            }
        }
        catch (Throwable th)
        {
            JudgeAssertUtil.throwExceptionDir(th, folder);
        }
        finally
        {
            FileUtilbc.close(fileOutputStream, inStream, downInStream, uploadOutput, writer);
            if (null != file && file.exists()) FileUtilbc.deleteFile(file);
            // assert downConn != null;
            // downConn.disconnect();
            // assert uploadConn != null;
            // uploadConn.disconnect();
        }
        
        return str;
    }
    
    public static String uploadFileNet(String downUrl, String uploadUrl, Map<String, Object> parameters)
    {
        InputStream downInStream = null;
        OutputStream uploadOutput = null;
        HttpURLConnection downConn = null;
        HttpURLConnection uploadConn = null;
        PrintWriter writer = null;
        String fileName = "";
        String msg = "";
        try
        {
            String boundary = Long.toHexString(System.currentTimeMillis()); // 随机边界
            downConn = getHttpConnection(downUrl);
            downInStream = downConn.getInputStream();
            
            uploadConn = getHttpConnection(uploadUrl);
            uploadOutput = uploadConn.getOutputStream();
            
            // 下载
            fileName = PubEnvUtil.isEmpty(fileName) ? RandomUtil.number(20) : fileName;
            Path target = Paths.get(FileUtilbc.getWorkServerPath() + "\\fileTemp", fileName);
            Files.createDirectories(target.getParent());
            Files.copy(downInStream, target, StandardCopyOption.REPLACE_EXISTING);
            File file = target.toFile();
            
            // Map<String, Object> cookie = (Map<String, Object>) parameters.get("Cookie");
            // uploadConn.setRequestProperty("yht_access_token",StringUtil.valueOfEmpty(cookie.get("yht_access_token")));
            //
            writer = new PrintWriter(new OutputStreamWriter(uploadOutput, "UTF-8"), true);
            // 发送文件数据
            writer.append("----------------------" + boundary).append(IPubCons.CRLF);
            writer.append("Content-Disposition: form-data; name=\"files\"; filename=\"" + file.getName() + "\"").append(IPubCons.CRLF);
            writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(file.getName())).append(IPubCons.CRLF);
            writer.append(IPubCons.CRLF).flush();
            
            // 发送请求参数
            writer.print(parameters);
            
            Path source = Paths.get(uploadConn.getURL().toURI());
            Files.copy(source, uploadOutput);
            writer.append(IPubCons.CRLF).flush(); // 结束行
            writer.append("--" + boundary + "--").append(IPubCons.CRLF);
            
            int responseCode = uploadConn.getResponseCode();
            System.out.println("Response Code: " + responseCode);
            // 删除临时文件。
            // Files.deleteIfExists(Paths.get(file.getPath()));
            msg = uploadConn.getResponseMessage();
        }
        catch (Throwable th)
        {
            JudgeAssertUtil.throwExceptionDir(th, folder);
        }
        finally
        {
            FileUtilbc.close(downInStream, uploadOutput, writer);
            // downConn.disconnect();
            // uploadConn.disconnect();
        }
        return msg;
    }
    
    /**
     * *********************************************************** <br>
     * *说明： 使用NIO上传 <br>
     * @see <br>
     * @param httpUrl
     * @param filePath @ * <br>
     * @void <br>
     * @methods pers.bc.utils.net.HttpFileUtil#uploadFile <br>
     * @author LiBencheng <br>
     * @date Created on 2024-10-29 <br>
     * @time 下午11:18:28 <br>
     * @version 1.0 <br>
     *************************************************************          <br>
     */
    public static void uploadFile(String httpUrl, String filePath, Map<String, Object> params)
    {
        String boundary = Long.toHexString(System.currentTimeMillis()); // 随机边界
        HttpURLConnection connection = null;
        OutputStream output = null;
        PrintWriter writer = null;
        try
        {
            // 获取URLConnection对象对应的输出流
            connection = getHttpConnection(httpUrl);
            output = connection.getOutputStream();
            writer = new PrintWriter(new OutputStreamWriter(output, "UTF-8"), true);
            // 发送文件数据
            File file = new File(filePath);
            writer.append("--" + boundary).append(IPubCons.CRLF);
            writer.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"").append(IPubCons.CRLF);
            writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(file.getName())).append(IPubCons.CRLF);
            
            writer.append(IPubCons.CRLF).flush();
            // 发送请求参数
            writer.print(params);
            
            Files.copy(file.toPath(), output);
            
            writer.append(IPubCons.CRLF).flush(); // 结束行
            writer.append("--" + boundary + "--").append(IPubCons.CRLF);
            
            int responseCode = connection.getResponseCode();
            System.out.println("Response Code: " + responseCode);
            
        }
        catch (Throwable th)
        {
            JudgeAssertUtil.throwExceptionDir(th, folder);
        }
        finally
        {
            FileUtilbc.flush(output);
            FileUtilbc.close(output, writer);
            connection.disconnect();
        }
        
    }
    
    /*************************************************************
     * <br>
     * *说明： 普通上传<br>
     * @see <br>
     * @params null <br>
     * @return <br>
     * @author libencheng <br>
     * @date Created on 2024/11/7 <br>
     * @time 13:33 <br>
     * @version 1.0 <br>
     *************************************************************          <br>
     */
    public static void uploadFile(String uploadUrl, String fileAllPath)
    {
        
        String boundary = "---------------------------boundary";
        String CRLF = "\r\n";
        String twoHyphens = "--";
        DataOutputStream outputStream = null;
        FileInputStream fileInputStream = null;
        try
        {
            File file = new File(fileAllPath);
            HttpURLConnection httpURLConnection = getHttpConnection(uploadUrl);
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
            outputStream = new DataOutputStream(httpURLConnection.getOutputStream());
            fileInputStream = new FileInputStream(file);
            // 添加表单字段
            outputStream.writeBytes(twoHyphens + boundary + RandomUtil.UUID() + CRLF);
            outputStream.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"" + CRLF);
            outputStream.writeBytes("Content-Type: application/octet-stream" + CRLF);
            outputStream.writeBytes(CRLF);
            
            // 写入文件数据
            byte[] buffer = new byte[1024];
            int length;
            while ((length = fileInputStream.read(buffer)) != -1)
            {
                outputStream.write(buffer, 0, length);
            }
            
            // 结束部分
            outputStream.writeBytes(CRLF);
            outputStream.writeBytes(twoHyphens + boundary + twoHyphens + CRLF);
            // 发送请求
            outputStream.flush();
            // String str = StreamUtil.InputStreamTOString(httpURLConnection.getInputStream(), "utf-8");
            // 获取响应
            int responseCode = httpURLConnection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK)
            {
                System.out.println("文件上传成功");
            }
            else
            {
                System.out.println("文件上传失败，响应码：" + responseCode);
            }
            
        }
        catch (Throwable th)
        {
            JudgeAssertUtil.throwExceptionDir(th, folder);
        }
        finally
        {
            FileUtilbc.close(outputStream, fileInputStream);
            // downConn.disconnect();
            // uploadConn.disconnect();
        }
    }
    
    /**
     * *********************************************************** <br>
     * *说明： 将MultipartFile转换为File <br>
     * @see <br>
     * @param multiFile
     * @return @ * <br>
     * @File <br>
     * @methods pers.bc.utils.net.HttpFileUtil#MultipartFileToFile <br>
     * @author LiBencheng <br>
     * @date Created on 2024-10-29 <br>
     * @time 下午10:35:21 <br>
     * @version 1.0 <br>
     *************************************************************          <br>
     */
    public static File MultipartFileToFile(MultipartFile multiFile)
    {
        InputStream in = null;
        OutputStream out = null;
        File file = null;
        try
        {
            String fileName = multiFile.getOriginalFilename();
            String prefix = fileName.substring(fileName.lastIndexOf("."));
            file = File.createTempFile(fileName, prefix);
            out = new FileOutputStream(file);
            in = multiFile.getInputStream();
            int read = 0;
            byte[] buffer = new byte[1024];
            while ((read = in.read(buffer, 0, 1024)) != -1)
                out.write(buffer, 0, read);
            
        }
        catch (Throwable th)
        {
            JudgeAssertUtil.throwExceptionDir(th, folder);
        }
        finally
        {
            FileUtilbc.close(in, out);
        }
        
        return file;
    }
    
    /**
     * *********************************************************** <br>
     * *说明：将文件转为base64 <br>
     * @see <br>
     * @param file
     * @return @ * <br>
     * @String <br>
     * @methods pers.bc.utils.net.HttpFileUtil#getBase64FromFile <br>
     * @author LiBencheng <br>
     * @date Created on 2024-10-29 <br>
     * @time 下午11:18:03 <br>
     * @version 1.0 <br>
     *************************************************************          <br>
     */
    public static String getBase64FromFile(File file)
    {
        FileInputStream in = null;
        ByteArrayOutputStream out = null;
        String base64Str = null;
        try
        {
            in = new FileInputStream(file);
            out = new ByteArrayOutputStream();
            int read = 0;
            byte[] buffer = new byte[1024];
            while ((read = in.read(buffer, 0, 1024)) != -1)
                out.write(buffer, 0, read);
            base64Str = Base64.encodeToString(out.toByteArray());
        }
        catch (Throwable th)
        {
            JudgeAssertUtil.throwExceptionDir(th, folder);
        }
        finally
        {
            FileUtilbc.close(in, out);
        }
        
        return base64Str;
    }
    
    static String getPram(Map<String, String> parameters) throws UnsupportedEncodingException
    {
        
        StringBuffer sb = new StringBuffer();// 处理请求参数s
        String params = "";// 编码之后的参数
        // 编码请求参数
        if (parameters.size() == 1)
        {
            for (String name : parameters.keySet())
            {
                sb.append(name).append("=").append(java.net.URLEncoder.encode(parameters.get(name), PubConsUtilbc.UTF_8));
            }
            params = sb.toString();
        }
        else
        {
            for (String name : parameters.keySet())
            {
                sb.append(name).append("=").append(java.net.URLEncoder.encode(parameters.get(name), PubConsUtilbc.UTF_8)).append("&");
            }
            String temp_params = sb.toString();
            params = temp_params.substring(0, temp_params.length() - 1);
        }
        
        return params;
    }
    
    private static HttpURLConnection getHttpConnection(String httpUrl) throws MalformedURLException, IOException
    {
        // URLConnection conn = new URL(httpUrl).openConnection();
        HttpURLConnection conn = (HttpURLConnection) new URL(httpUrl).openConnection();
        // 设置通用的请求属性
        conn.setRequestProperty("Accept", "*/*");
        conn.setRequestProperty("Content-Type", "multipart/form-data;charset=UTF-8");
        conn.setRequestProperty("Connection", "keep-alive");
        conn.setRequestProperty("User-Agent",
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36 Edg/141.0.0.0");
        // 是建立连接的超时时间；
        conn.setConnectTimeout(30000);
        // 是传递数据的超时时间
        conn.setReadTimeout(500000);
        // 发送POST请求必须设置如下两行
        conn.setDoOutput(true);
        conn.setDoInput(true);
        // conn.setRequestMethod("POST");
        
        return conn;
    }
    
    /**
     * @Description: < 下载链接转换为bytes>
     * @Author: donghang
     * @Date: 2024/12/4 21:33
     **/
    public static String uploadUrlToByte(String downUrl)
    {
        InputStream downInStream = null;
        HttpURLConnection downConn = null;
        String str = "";
        try
        {
            downConn = getHttpConnection(downUrl);
            // 从连接的输入流中取得回执信息
            downInStream = downConn.getInputStream();
            byte[] bytes = StreamUtil.InputStreamTOByte(downInStream);
            str = Base64.encodeToString(bytes);
        }
        catch (Throwable th)
        {
            JudgeAssertUtil.throwExceptionDir(th, folder);
        }
        return str;
    }
}
